package pages;

import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import database.DBUtils;

import templates.Template;

/**
 * Servlet implementation class index
 */
public class index extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public index() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		String username = request.getUserPrincipal().getName();

		// get name from username
		
		
		try {
			String name = username;
			name = getUserName(username);
			if (name == null)
				throw new Exception("Cannot get user name");
			

			Template template = new Template("main_page");
			template.addChange("username", name);
	

			response.getOutputStream().print(template.createPage("Welcome to Instruments Labaratory!",
							LMUtils.getUserLogin(request)));
		} catch (Exception e) {
			try {
				String userLogin = LMUtils.getUserLogin(request);
				response.getWriter().print(
						ErrorPage.generateErrorPage(e.getMessage(), userLogin));
			} catch (InternalErrorException e1) {
				response.getWriter().print(e1.getMessage());
			}
		}

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	}

	
	private static String getUserName(String userLogin)
	{
		Connection conn = null;
		PreparedStatement selectUserStmt = null;
		ResultSet rs = null;
		try {
			conn = DBUtils.getConnection();
			selectUserStmt = conn.prepareStatement("SELECT `Name` FROM `users` WHERE `Login` = ?;");
			selectUserStmt.setString(1, userLogin);
			rs = selectUserStmt.executeQuery();
			if (rs == null || !rs.next()) {
				return null;
			} else {
				return rs.getString("Name");

			}
		} catch (Exception e) {
			return null;
		} finally {
			DBUtils.close(rs);
			DBUtils.close(selectUserStmt);
			DBUtils.close(conn);
		}
	}
	

}


